package org.abettor.pushbox.activity2;

/**
 * 显示地图详情的activity
 */
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.activity.NetBoxShowResultActivity;
import org.abettor.pushbox.activity.NetPushBoxMapActivity;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.DownloadMap;
import org.abettor.pushbox.download.ParaDownloadRetValue;
import org.abettor.pushbox.map.AsyncGenerateNetMapThumbImage;
import org.abettor.pushbox.map.Boxmap;
import org.abettor.pushbox.map.BoxmapUtil;
import org.abettor.pushbox.map.AsyncGenerateNetMapThumbImage.NetImageCallBack;
import org.abettor.pushbox.model.NetPushBoxMapBean;
import org.abettor.pushbox.model.NotifyBean;
import org.abettor.pushbox.upload.SendFlowerOrEggUpload;
import org.abettor.pushbox.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class ShowMapDetailActivity extends Activity {
	// 生成缩略图的操作
	private AsyncGenerateNetMapThumbImage netThumbImage = null;
	private ProgressDialog progress;// 进度条对话框
	private Handler mHandler = new Handler();
	private DownloadMap download = null;
	private int map_id = -1;// 地图的id
	private NetPushBoxMapBean netMapBean;// 地图的bean
	private ImageView imageView;// 显示图片的控件
	private NetImageCallBack callback;// 进行回调显示的类
	private Button flowerButton;// 送鲜花的button
	private Button eggButton;// 扔臭鸡蛋的button
	private Button resolvedDetailButton;// 解决的详情的button
	private Button replyDetailButton;// 回复详情的button
	private Button startButton;// 开始推箱子或者看结果的button
	private Button userDetailButton;//查看用户详情的button
	private TextView upporTextView;// 上传者的文本文件
	private TextView updateTextView;// 上传的时间
	private TextView psTextView;// 附言的textview
	private TextView eggFlowerTextView;// 鲜花臭鸡蛋的个数
	private TextView resolvedCountTextView;// 解决的人数
	private TextView replyCountTextView;// 回复的人数
	private TextView isMyResolvedTextView;// 是否我已解决过
	private SendFlowerOrEggUpload uploadBean;// 送鲜花的bean;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/*-----------------------广告-------------------*/
	private final int SHOW_AD = 13579;
	private YoumiManager youmi = new YoumiManager(this);
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 70) {
					youmi.showYoumi(YoumiManager.Position.middle, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	// 按钮点击按钮的监听器
	private class ButtonOnclickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (v == flowerButton) {
				sendFlower();
			} else if (v == eggButton) {
				sendEgg();
			} else if (v == resolvedDetailButton) {
				resovedDetail();
			} else if (v == replyDetailButton) {
				replyDetail();
			} else if (v == startButton) {
				doAnswer(netMapBean.getId());
			}else if(v==userDetailButton){
				doViewUserDetail(netMapBean.getUploaderId(),netMapBean.getUploader());
			}
		}
	}
	/**
	 * 查看用户的详情
	 * 
	 * @param id
	 */
	private void doViewUserDetail(int id,String value) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		extras.putString("nick_name", value);
		in.putExtras(extras);
		in.setClass(ShowMapDetailActivity.this, ShowUserDetailActivity.class);
		startActivity(in);
	}
	// 进行解答的操作
	private void doAnswer(int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		in.putExtras(extras);
		if (netMapBean.isMyresolved()) {// 判断是否本人已经解决
			// 本人已解决，先查寻本地答案文件是否已经存在,不存在的话，打开地图的文件，存在的话打开解答后的地图
			String filePath = Config.getNetBasePath() + File.separator
					+ String.valueOf(id) + ".step";
			File file = new File(filePath);
			if (!file.exists()) {
				in.setClass(ShowMapDetailActivity.this,
						NetPushBoxMapActivity.class);
			} else {
				in.setClass(ShowMapDetailActivity.this,
						NetBoxShowResultActivity.class);
			}
		} else {// 本人未解决的条件
			in.setClass(ShowMapDetailActivity.this, NetPushBoxMapActivity.class);
		}
		startActivity(in);
	}
	//显示留言的操作
	private void replyDetail(){
		Intent intent = new Intent();
		intent.setClass(this, MessageBoardActivity.class);
		Bundle extras = new Bundle();
		extras.putInt("_id", map_id);
		intent.putExtras(extras);
		this.startActivity(intent);
	}
	//显示解决了用户详情的列表
	private void resovedDetail(){
		Intent intent = new Intent();
		intent.setClass(this, ResovedMapUserList.class);
		Bundle extras = new Bundle();
		extras.putInt("_id", map_id);
		intent.putExtras(extras);
		this.startActivity(intent);
	}
	// 送鲜花的操作
	private void sendFlower() {
		SendFlowerOrEggUpload.UpdateShowMapDetail call = new SendFlowerOrEggUpload.UpdateShowMapDetail() {
			@Override
			public void update(int count) {
				eggFlowerTextView.setText(count+"/"+netMapBean.getEggCount());
				netMapBean.setFlowerCount(String.valueOf(count));
			}
		};
		uploadBean.postFlower(call,map_id);
	}
	//扔鸡蛋的操作
	private void sendEgg(){
		SendFlowerOrEggUpload.UpdateShowMapDetail call = new SendFlowerOrEggUpload.UpdateShowMapDetail() {
			@Override
			public void update(int count) {
				eggFlowerTextView.setText(netMapBean.getFlowerCount()+"/"+count);
				netMapBean.setEggCount(String.valueOf(count));
			}
		};
		uploadBean.postEgg(call,map_id);
	}
	// 设置各个属性
	private void setViewMessage() {
		if (netMapBean != null) {
			upporTextView.setText(netMapBean.getUploader());
			updateTextView.setText(sdf.format(netMapBean.getUploadDate()));
			eggFlowerTextView.setText(netMapBean.getFlowerCount() + "/"
					+ netMapBean.getEggCount());
			resolvedCountTextView.setText(netMapBean.getResolvedCount());
			replyCountTextView.setText(netMapBean.getRplyCount());
			if (netMapBean.isMyresolved()) {
				isMyResolvedTextView.setText(this
						.getText(R.string.showmap_detail_activity_yes));
			} else {
				isMyResolvedTextView.setText(this
						.getText(R.string.showmap_detail_activity_no));
			}
			if (netMapBean.getPs() != null) {
				psTextView.setText(netMapBean.getPs());
			} else {
				psTextView.setText(this
						.getText(R.string.showmap_detail_activity_none));
			}
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		int notifyId = getIntent().getIntExtra(NotifyBean.NOTIFY_TAG, -1);
		if(notifyId >= 0)
		{
			NotificationManager notiMgmt = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			notiMgmt.cancel(NotifyBean.NOTIFY_TAG, notifyId);
		}

		// 读取map的id
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		map_id = extras.getInt("_id");
		readMapFromNet();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_map_detail_activity);
		download = new DownloadMap(this);
		uploadBean = new SendFlowerOrEggUpload(this);
		// 初始化的操作
		init();
	}

	// 初始化的操作
	private void init() {
		flowerButton = (Button) this.findViewById(R.id.throwflower);
		flowerButton.setOnClickListener(new ButtonOnclickListener());
		eggButton = (Button) this.findViewById(R.id.throwegg);
		eggButton.setOnClickListener(new ButtonOnclickListener());
		resolvedDetailButton = (Button) this
				.findViewById(R.id.resolved_count_detail);
		resolvedDetailButton.setOnClickListener(new ButtonOnclickListener());
		replyDetailButton = (Button) this.findViewById(R.id.reply_count_detail);
		replyDetailButton.setOnClickListener(new ButtonOnclickListener());
		userDetailButton = (Button) this.findViewById(R.id.user_detail);
		userDetailButton.setOnClickListener(new ButtonOnclickListener());
		startButton = (Button) this.findViewById(R.id.button_start);
		startButton.setOnClickListener(new ButtonOnclickListener());
		upporTextView = (TextView) this.findViewById(R.id.uppor);
		updateTextView = (TextView) this.findViewById(R.id.update);
		psTextView = (TextView) this.findViewById(R.id.showmap_detail_ps);
		eggFlowerTextView = (TextView) this.findViewById(R.id.fl_egg_count);
		resolvedCountTextView = (TextView) this
				.findViewById(R.id.resolved_count);
		replyCountTextView = (TextView) this.findViewById(R.id.reply_count);
		isMyResolvedTextView = (TextView) this.findViewById(R.id.is_myresolved);
		youmiDelayThread.start();
	}

	// 读取网络消息
	private void readMapFromNet() {
		progress = new ProgressDialog(this);
		progress.setTitle(R.string.showmap_detail_activity);
		progress.setMessage(this
				.getText(R.string.showmap_detail_activity_loading));
		progress.show();
		Thread thread = new Thread() {
			@Override
			public void run() {
				String ret = download.readMapDetailFromNet(map_id);
				progress.dismiss();
				if (ret == null) {
					readMessageError();
					return;
				}
				netMapBean = ParaDownloadRetValue.paraNetMapDetail(ret);
				if (netMapBean == null) {
					readMessageError();
					return;
				}
				// 调用设置界面的接口
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						setViewData();
					}
				});
			}
		};
		thread.start();
	}

	// 读取网络信息失败,显示的对话框
	private void readMessageError() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						ShowMapDetailActivity.this);
				final AlertDialog alert = builder.create();
				alert.setTitle(R.string.error);
				alert.setMessage(ShowMapDetailActivity.this
						.getText(R.string.read_net_error));
				alert.setButton(
						DialogInterface.BUTTON_POSITIVE,
						ShowMapDetailActivity.this.getText(android.R.string.ok),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								readMapFromNet();
							}
						});
				alert.setButton(DialogInterface.BUTTON_NEGATIVE,
						ShowMapDetailActivity.this
								.getText(android.R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								ShowMapDetailActivity.this.finish();
							}
						});
				alert.show();
			}
		});
	}

	// 设置网络的消息
	private void setViewData() {
		imageView = (ImageView) this.findViewById(R.id.push_box_image);
		// 回调接口
		callback = new NetImageCallBack() {
			@Override
			public void processImage(Bitmap bit) {
				imageView.setImageBitmap(bit);
			}
		};
		// 进行回调显示的类
		netThumbImage = new AsyncGenerateNetMapThumbImage(imageView.getWidth(),
				imageView.getHeight(), callback, ShowMapDetailActivity.this) {
			@Override
			protected Bitmap generateImage() {
				// 判断缩略图的文件是否存在,存在的话直接读取文件
				String thrumb = getThumbNailPath() + File.separator
						+ getNetMapId() + ".bigthrumb";
				Bitmap bmp = null;
				File file = new File(thrumb);
				if (file.exists()) {// 读取存在的文件
					bmp = readBitmap(file);
				}
				if (bmp != null) {
					return bmp;
				}
				byte[] buf = null;
				try {
					buf = readFile();
				} catch (Exception e) {
				}
				if (buf == null) {// 数据为空,从网络上读取
					buf = readMapFromNet();
				}
				if (buf == null) {
					return null;
				}
				Boxmap map = BoxmapUtil.paraArrayToMap(buf);// 生成地图
				mapThumbnailDraw.setMap(map);
				bmp = mapThumbnailDraw.draw();
				// 在本地缓存一份
				generateThumbnail(bmp, thrumb);
				return bmp;
			}

			@Override
			public int getNetMapId() {
				return map_id;
			}

			@Override
			public String getMapFilePath() {
				return Config.getNetBasePath();
			}

			@Override
			public String getThumbNailPath() {
				return Config.getNetBasePath();
			}
		};
		// 执行回调的操作
		netThumbImage.start();
		// 填重数据的操作
		setViewMessage();
		// 显示附言的操作
		// psTextView = (TextView) this.findViewById(R.id.showmap_detail_ps);
	}
}
